package com.timedomain.him.remake.ui;

import android.app.TimePickerDialog;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.os.Bundle;
import android.support.annotation.NonNull;
import android.text.TextUtils;
import android.util.TypedValue;
import android.view.View;
import android.view.ViewGroup;
import android.view.ViewTreeObserver;
import android.view.animation.AlphaAnimation;
import android.view.animation.Animation;
import android.view.animation.AnimationUtils;
import android.widget.AbsListView;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.CheckBox;
import android.widget.CompoundButton;
import android.widget.ImageButton;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.RadioButton;
import android.widget.TextView;
import android.widget.TimePicker;
import android.widget.ToggleButton;

import com.timedomain.him.remake.R;
import com.timedomain.him.remake.core.ChannelCreator;
import com.timedomain.him.remake.core.ListPlayer;
import com.timedomain.him.remake.core.PhoneCall;
import com.timedomain.him.remake.core.SimplePlayer;
import com.timedomain.him.remake.models.ChatMessage;
import com.timedomain.him.remake.models.CompanionPhoneCall;
import com.timedomain.him.remake.models.MorningCall;
import com.timedomain.him.remake.ui.common.CallingActivity;
import com.timedomain.him.remake.ui.common.PlayerActivity;
import com.timedomain.him.remake.utils.ActiveChatManager;
import com.timedomain.him.remake.utils.AppSettings;
import com.timedomain.him.remake.utils.BaseActivity;
import com.timedomain.him.remake.utils.DB;
import com.timedomain.him.remake.utils.FileUtils;
import com.timedomain.him.remake.utils.MorningCallManager;
import com.timedomain.him.remake.utils.NotificationUtils;
import com.timedomain.him.remake.utils.TimeUtils;
import com.timedomain.him.remake.yggdrasil.Selection;
import com.timedomain.him.remake.yggdrasil.TheWorldTree;
import com.timedomain.him.remake.yggdrasil.YieldChatMessage;
import com.timedomain.him.remake.yggdrasil.YieldSelection;

import org.jetbrains.annotations.NotNull;
import org.jetbrains.annotations.Nullable;

import java.util.ArrayList;
import java.util.List;

public class MessageActivity extends BaseActivity {

    private LinearLayout pageCallLog;
    private ListView listChatCallLog;
    private LinearLayout pageChat;
    private LinearLayout panelMessageInput;
    private TextView listChatOptionsEmpty;
    private ListView listChatOptions;
    private Button btnSend;
    private TextView txtMessageInput;
    private ListView listChatMain;
    private RadioButton btnPhonecallTab;
    private RadioButton btnMessageTab;
    private void initUI(){	 pageCallLog = (LinearLayout)findViewById(R.id.pageCallLog);
        listChatCallLog = (ListView)findViewById(R.id.listChatCallLog);
        pageChat = (LinearLayout)findViewById(R.id.pageChat);
        panelMessageInput = (LinearLayout)findViewById(R.id.panelMessageInput);
        listChatOptionsEmpty = (TextView)findViewById(R.id.listChatOptionsEmpty);
        listChatOptions = (ListView)findViewById(R.id.listChatOptions);
        btnSend = (Button)findViewById(R.id.btnSend);
        txtMessageInput = (TextView)findViewById(R.id.txtMessageInput);
        listChatMain = (ListView)findViewById(R.id.listChatMain);
        btnPhonecallTab = (RadioButton)findViewById(R.id.btnPhonecallTab);
        btnMessageTab = (RadioButton)findViewById(R.id.btnMessageTab);
        btnMessageTab.setOnCheckedChangeListener((buttonView, isChecked) -> {
            pageChat.setVisibility(isChecked ? View.VISIBLE : View.GONE);
            pageCallLog.setVisibility(isChecked ? View.GONE : View.VISIBLE);
        });
        txtMessageInput.setOnClickListener(v -> panelMessageInput.setVisibility(View.VISIBLE));
        chatAdapter = new ChatAdapter(this);
        listChatMain.setAdapter(chatAdapter);


        callAdapter = new CompanionCallAdapter(this);
        listChatCallLog.setAdapter(callAdapter);
        selectionAdapter = new SelectionAdapter(this);
        listChatOptions.setAdapter(selectionAdapter);

        morningCallHour = AppSettings.morningCallHour;
        morningCallMinute = AppSettings.morningCallMinute;
        loadCompanionCallData();
    }

    private void loadCompanionCallData(){
        callAdapter.clear();
        callAdapter.addAll(DB.CompanionPhoneCall.Query());
    }

    ChatAdapter chatAdapter;
    CompanionCallAdapter callAdapter;
    SelectionAdapter selectionAdapter;

    TheWorldTree world;

    public void reloadState(){
        if(isDestroyed()){return;}
        NotificationUtils.removeAllMessageNotification(this);
        offset = 0;
        chatAdapter.clear();
        loadMore();
        world.loadState(AppSettings.savedWorldState);
        doTicks();
    }

    public class OnNewMessageBroadcastReceiver extends BroadcastReceiver {

        @Override
        public void onReceive(Context context, Intent intent) {
            MessageActivity.this.reloadState();
        }
    }

    private OnNewMessageBroadcastReceiver newMessageBroadcastReceiver;

    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_chat);
        initUI();
        new Thread(() -> {
            TheWorldTree a = new TheWorldTree(MessageActivity.this);
            world = a;
            if(TimeUtils.getTimeStampIgnoreTimeZone() - AppSettings.lastChatMessageTime < 30 * 60 * 1000){
                a.loadState(AppSettings.savedWorldState);
            }
            else{
                a.reset();
            }
            runOnUiThread(() -> {
                loadMore();
                doTicks();
                IntentFilter intentFilter = new IntentFilter(ActiveChatManager.BROADCAST_NEW_MESSAGE);
                if(!isDestroyed()) {
                    registerReceiver((newMessageBroadcastReceiver = new OnNewMessageBroadcastReceiver()), intentFilter);
                }
            });
        }).start();

        setTimerEnabled(true);
        setTimerInterval(400);
    }

    @Override
    protected void onResume() {
        super.onResume();
        NotificationUtils.removeAllMessageNotification(this);
    }

    @Override
    public void onBackPressed() {
        if(panelMessageInput.getVisibility() == View.VISIBLE){
            panelMessageInput.setVisibility(View.GONE);
            return;
        }
        super.onBackPressed();
    }

    private int messageCd = 0;
    private boolean inMessageLoop = true;
    @Override
    protected void onTimer() {
        if(inMessageLoop && world != null){
            messageCd--;
            if(messageCd < 0){
                messageCd = 5;
                doTicks();
            }
        }
        checkPlayerStopped();
    }

    public void doTicks(){
        try {
            int maxStep = 200;
            while (maxStep-- > 0) {
                world.nextTick();
                world.reset();
            }
        } catch (YieldChatMessage yieldChatMessage) {
            onMessage(yieldChatMessage.message);
            inMessageLoop = true;
        } catch (YieldSelection yieldSelection) {
            inMessageLoop = false;
            onSelection(yieldSelection.selections);
        }
    }

    public void onMessage(ChatMessage msg){
        listChatOptions.setVisibility(View.GONE);
        listChatOptionsEmpty.setVisibility(View.VISIBLE);
        btnSend.setEnabled(false);
        if(chatAdapter.getCount() == 0 || TimeUtils.getTimeStampIgnoreTimeZone() - chatAdapter.getItem(chatAdapter.getCount()-1).date > 10 * 60 * 1000){
            ChatMessage timeIndicator = new ChatMessage(TimeUtils.getTimeStampIgnoreTimeZone() - 1,"",ChatMessage.TYPE_TIME,"","");
            insertMessageToDB(timeIndicator);
        }
        insertMessageToDB(msg);
        chatAdapter.notifyDataSetChanged();
        inMessageLoop  =true;
        messageCd = 5;
        AppSettings.savedWorldState = world.saveState();
        AppSettings.lastChatMessageTime = TimeUtils.getTimeStampIgnoreTimeZone();
        AppSettings.saveSettings(this);
        if(msg.type == ChatMessage.TYPE_PHONE_CALL){
            CallingActivity.startNewCall(this,msg.audioFile,true);
            String duration = "--";
            try(SimplePlayer sp = new SimplePlayer(ChannelCreator.FromFile(this,msg.audioFile))){
                duration = TimeUtils.msToTimeStr(sp.getDuration());
            }
            CompanionPhoneCall call = new CompanionPhoneCall(
                    FileUtils.getFileNameWithoutExtension(msg.audioFile),
                    msg.audioFile,
                    TimeUtils.getTimeStampIgnoreTimeZone(),
                    duration
            );
            DB.CompanionPhoneCall.Add(call);
            loadCompanionCallData();
        }
        if(msg.type == ChatMessage.TYPE_START_NIGHT_MODE){
            AppSettings.readedChatMessageTime = AppSettings.lastChatMessageTime +1;
            AppSettings.saveSettings(this);
            NightActivity.startNightMode(this);
            finish();
        }
        if(msg.type == ChatMessage.TYPE_CLEAR_MORNING_TIME){
            AppSettings.nightChat  = true;
            AppSettings.nightChatRequiredMorningCall = false;
            AppSettings.nightChatDay = TimeUtils.toDateStamp(TimeUtils.getTimeStampIgnoreTimeZone());
            AppSettings.saveSettings(this);
            MorningCallManager.setNextMorningCall(this);
        }
    }

    private int morningCallHour=6,morningCallMinute=0;



    private void insertMessageToDB(ChatMessage message){
        message.date = TimeUtils.getTimeStampIgnoreTimeZone();
        if(message.type < -2){
            return;
        }
        chatAdapter.add(message);
        listChatMain.post(()->listChatMain.setSelection(chatAdapter.getCount()-1));
        DB.ChatMessage.Add(message);
        offset++;
    }

    public void onSelection(List<Selection> selections){
        AppSettings.savedWorldState = world.saveState();
        AppSettings.lastChatMessageTime = TimeUtils.getTimeStampIgnoreTimeZone();
        if(AppSettings.savedWorldState.equals(TheWorldTree.LEAF_ENTRY)){
            AppSettings.readedChatMessageTime = AppSettings.lastChatMessageTime +1;
        }
        AppSettings.saveSettings(this);
        inMessageLoop = false;
        listChatOptions.setVisibility(View.VISIBLE);
        listChatOptionsEmpty.setVisibility(View.GONE);
        selectedSelection = null;
        btnSend.setEnabled(false);
        selectionAdapter.clear();
        selectionAdapter.addAll(selections);

        long timeOfDay = TimeUtils.getTimeStampIgnoreTimeZone() - TimeUtils.dateStampToTimeStamp(TimeUtils.toDateStamp(TimeUtils.getTimeStampIgnoreTimeZone()));

        if(timeOfDay < 6L * 60L * 60L * 1000L){
            for (int i = 0; i < selectionAdapter.getCount(); i++) {
                if(selectionAdapter.getItem(i).nextLeaf.equals("[NightResponse]")){
                    selectionAdapter.remove(selectionAdapter.getItem(i));
                    break;
                }
            }
        }

        selectionAdapter.notifyDataSetChanged();
    }

    private Selection selectedSelection;
    public void onSelectionClick(View v){
        Selection sel = (Selection) v.getTag();
        if(sel.buttonTitle.contains(specialSelectionTimeSelect)){
            TimePickerDialog timePickerDialog = new TimePickerDialog(this, new TimePickerDialog.OnTimeSetListener() {
                @Override
                public void onTimeSet(TimePicker view, int hourOfDay, int minute) {
                    int min = 4 * 60 + 30;
                    int max = 9 * 60 + 59;
                    int current = hourOfDay * 60 + minute;
                    if(current < min || current > max){
                        showToast("这个时间范围不合适，换一个试试吧");
                        return;
                    }
                    morningCallHour = hourOfDay;
                    morningCallMinute = minute;
                    selectedSelection = sel;
                    selectionAdapter.notifyDataSetChanged();
                    btnSend.setEnabled(true);
                    txtMessageInput.setText(selectedSelection.sendingMessage
                            .replace("{TIME}",hourOfDay +":"+(minute < 10 ? ("0"+minute) : (""+minute))));
                }
            },morningCallHour,morningCallMinute,true);
            timePickerDialog.show();
            return;
        }
        selectedSelection = sel;
        selectionAdapter.notifyDataSetChanged();
        btnSend.setEnabled(true);
        txtMessageInput.setText(selectedSelection.sendingMessage);
    }

    public void sendSelection(View v){
        btnSend.setEnabled(false);
        String pendingMessage = txtMessageInput.getText().toString();
        txtMessageInput.setText("");
        if(selectedSelection.buttonTitle.contains(specialSelectionTimeSelect)){
            AppSettings.nightChat = true;
            AppSettings.nightChatRequiredMorningCall = true;
            AppSettings.morningCallHour = morningCallHour;
            AppSettings.morningCallMinute = morningCallMinute;
            long nextDay = TimeUtils.dateStampToTimeStamp(1+TimeUtils.toDateStamp(TimeUtils.getTimeStampIgnoreTimeZone()));
            nextDay += (morningCallHour - 4L) * 60L * 60L * 1000L;
            nextDay += (morningCallMinute) * 60L * 1000L;
            AppSettings.manualMorningCallDate = nextDay;
            AppSettings.nightChatDay = TimeUtils.toDateStamp(TimeUtils.getTimeStampIgnoreTimeZone());
            AppSettings.saveSettings(this);
            MorningCallManager.setNextMorningCall(this);
        }
        try {
            world.applySelection(selectedSelection);
        } catch (YieldChatMessage yieldChatMessage) {
            ChatMessage yieldMessage = yieldChatMessage.message;
            yieldMessage.content = pendingMessage;
            onMessage(yieldMessage);
        }
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        if(newMessageBroadcastReceiver != null){
            unregisterReceiver(newMessageBroadcastReceiver);
        }
        if(chatMessagePlayer != null){
            chatMessagePlayer.close();
            chatMessagePlayer = null;
        }

    }

    int offset = 0;
    boolean inLoading = false;
    public void loadMore(){
        inLoading = true;
        int positionToSave = listChatMain.getFirstVisiblePosition();

        List<ChatMessage> loadedResult = DB.ChatMessage.Query(offset);// TODO

        int loadedCount = loadedResult.size();
        offset += loadedCount;

        final int positionToRestore = positionToSave + loadedCount+1;
        if(chatAdapter.getCount() > 0 && chatAdapter.getItem(0).type == ChatMessage.TYPE_LOAD_INDICATOR){
            chatAdapter.remove(chatAdapter.getItem(0));
        }

        if(loadedCount != 0) {
            for (int i = 0; i < loadedCount; i++) {
                chatAdapter.insert(loadedResult.get(i), 0);
            }
            if(loadedCount >= 20){
                chatAdapter.insert(new ChatMessage(0L, "" , ChatMessage.TYPE_LOAD_INDICATOR, "", ""), 0);
            }

            listChatMain.post(() -> {
                listChatMain.setSelection(positionToRestore);
                listChatMain.post(()->{
                    inLoading = false;
                });
            });

        }

        chatAdapter.notifyDataSetChanged();
    }

    private SimplePlayer chatMessagePlayer = null;
    private int playingMessageId = -1;

    private void checkPlayerStopped(){
        if(chatMessagePlayer == null || chatMessagePlayer.isStopped()){
            if(playingMessageId != -1){
                playingMessageId = -1;
                chatAdapter.notifyDataSetChanged();
            }
        }
    }

    private void playMessage(ChatMessage cm){
        if(chatMessagePlayer != null){chatMessagePlayer.close();}
        if(playingMessageId == cm.id){
            return;
        }
        chatMessagePlayer = new SimplePlayer(ChannelCreator.FromFile(this,cm.audioFile));
        chatMessagePlayer.start();
        chatAdapter.notifyDataSetChanged();
        playingMessageId = cm.id;
    }

    public void clickMessage(View v){

        ChatMessage cm = (ChatMessage) v.getTag();
        if(cm.type == ChatMessage.TYPE_PHONE_CALL){
            CallingActivity.startNewCall(this,cm.audioFile,true);
        }
        if(cm.type == ChatMessage.TYPE_VOICE || (cm.type == ChatMessage.TYPE_MESSAGE && !TextUtils.isEmpty(cm.audioFile))){
            playMessage(cm);
        }

    }

    private static final String specialSelectionTimeSelect = "[TimeSelect]";

    public class ChatAdapter extends ArrayAdapter<ChatMessage>{
        public ChatAdapter(@NotNull Context context) {
            super(context, R.layout.list_chatbubble);
        }

        @NotNull
        @Override
        public View getView(int position, @Nullable View convertView, @NotNull ViewGroup parent) {
            if(convertView == null){
                convertView = getLayoutInflater().inflate(R.layout.list_chatbubble,null,false);
            }
            TextView cbTime = (TextView)convertView.findViewById(R.id.cbTime);
            LinearLayout cbResponse = (LinearLayout)convertView.findViewById(R.id.cbResponse);
            TextView cbTextResponse = (TextView)convertView.findViewById(R.id.cbTextResponse);
            LinearLayout cbResponseHeader = (LinearLayout)convertView.findViewById(R.id.cbResponseHeader);
            TextView cbResponseHeaderText = (TextView)convertView.findViewById(R.id.cbResponseHeaderText);
            ImageView cbIconVoice = (ImageView)convertView.findViewById(R.id.cbIconVoice);
            ImageView cbIconRead = (ImageView)convertView.findViewById(R.id.cbIconRead);
            ImageView cbIconPhone = (ImageView)convertView.findViewById(R.id.cbIconPhone);
            TextView cbTextSend = (TextView)convertView.findViewById(R.id.cbTextSend);
            View cbLoading = convertView.findViewById(R.id.cbLoading);
            View cbIconShare = convertView.findViewById(R.id.cbIconShare);
            View cbResponseDivider = convertView.findViewById(R.id.cbResponseDivider);
            cbTime.setVisibility(View.GONE);
            cbResponse.setVisibility(View.GONE);
            cbTextResponse.setVisibility(View.GONE);
            cbResponseHeader.setVisibility(View.GONE);
            cbResponseHeaderText.setVisibility(View.GONE);
            cbIconVoice.setVisibility(View.GONE);
            cbIconRead.setVisibility(View.GONE);
            cbIconPhone.setVisibility(View.GONE);
            cbIconShare.setVisibility(View.GONE);
            cbTextSend.setVisibility(View.GONE);
            cbLoading.setVisibility(View.GONE);
            cbResponseDivider.setVisibility(View.GONE);
            cbIconVoice.clearAnimation();
            cbIconRead.clearAnimation();
            ChatMessage message = getItem(position);
            convertView.setTag(message);
            if(message.type == ChatMessage.TYPE_LOAD_INDICATOR){
                cbLoading.setVisibility(View.VISIBLE);
                if(!inLoading){
                    setTimeout(MessageActivity.this::loadMore,500);
                }

                return convertView;
            }

            if(message.type == ChatMessage.TYPE_SEND_MESSAGE){
                cbTextSend.setVisibility(View.VISIBLE);
                cbTextSend.setText(message.content);
            }
            if(message.type == ChatMessage.TYPE_TIME){
                cbTime.setVisibility(View.VISIBLE);
                cbTime.setText(TimeUtils.getTimeDesc(message.date));
            }
            if(message.type == ChatMessage.TYPE_MESSAGE){
                cbResponse.setVisibility(View.VISIBLE);
                if(!TextUtils.isEmpty(message.audioFile)){
                    cbResponseHeader.setVisibility(View.VISIBLE);
                    cbResponseHeaderText.setVisibility(View.VISIBLE);
                    cbResponseHeaderText.setText(message.extra);
                    cbIconVoice.setVisibility(View.VISIBLE);
                    if(playingMessageId == message.id){
                        AlphaAnimation alphaAnimation1 = new AlphaAnimation(0.1f, 1.0f);

                        alphaAnimation1.setDuration(1000);

                        alphaAnimation1.setRepeatCount(Animation.INFINITE);

                        alphaAnimation1.setRepeatMode(Animation.REVERSE);

                        cbIconVoice.setAnimation(alphaAnimation1);

                        alphaAnimation1.start();
                    }
                    cbResponse.setTag(message);
                    cbResponse.setOnClickListener(MessageActivity.this::clickMessage);
                    cbResponseDivider.setVisibility(View.VISIBLE);
                }
                cbTextResponse.setText(message.content);
                cbTextResponse.setVisibility(View.VISIBLE);
            }
            if(message.type == ChatMessage.TYPE_PHONE_CALL){
                cbResponse.setVisibility(View.VISIBLE);
                cbResponseHeader.setVisibility(View.VISIBLE);
                cbResponseHeaderText.setVisibility(View.VISIBLE);
                cbResponseHeaderText.setText(message.content);
                cbIconPhone.setVisibility(View.VISIBLE);
                cbResponse.setTag(message);
                cbResponse.setOnClickListener(MessageActivity.this::clickMessage);
            }
            if(message.type == ChatMessage.TYPE_VOICE){
                cbResponse.setVisibility(View.VISIBLE);
                cbResponseHeader.setVisibility(View.VISIBLE);
                cbResponseHeaderText.setVisibility(View.VISIBLE);
                cbResponseHeaderText.setText(message.content);
                cbIconRead.setVisibility(View.VISIBLE);
                if(playingMessageId == message.id){
                    AlphaAnimation alphaAnimation1 = new AlphaAnimation(0.1f, 1.0f);

                    alphaAnimation1.setDuration(1000);

                    alphaAnimation1.setRepeatCount(Animation.INFINITE);

                    alphaAnimation1.setRepeatMode(Animation.REVERSE);

                    cbIconRead.setAnimation(alphaAnimation1);

                    alphaAnimation1.start();
                }
                cbResponse.setTag(message);
                cbResponse.setOnClickListener(MessageActivity.this::clickMessage);
            }
            if(message.type == ChatMessage.TYPE_SHARE_SONG){
                cbResponse.setVisibility(View.VISIBLE);
                cbResponseHeader.setVisibility(View.VISIBLE);
                cbResponseHeaderText.setVisibility(View.VISIBLE);
                cbResponseHeaderText.setText(message.content);
                cbIconShare.setVisibility(View.VISIBLE);
                cbResponse.setTag(message);
                cbResponse.setOnClickListener(MessageActivity.this::clickMessage);
            }

            return convertView;
        }

    }

    public class SelectionAdapter extends ArrayAdapter<Selection>{

        public SelectionAdapter(@NonNull @NotNull Context context) {
            super(context, R.layout.list_selection);
        }

        @NonNull
        @NotNull
        @Override
        public View getView(int position, @android.support.annotation.Nullable @Nullable View convertView, @NonNull @NotNull ViewGroup parent) {
            if(convertView == null){
                convertView = getLayoutInflater().inflate(R.layout.list_selection,null,false);
            }
            convertView.setTag(getItem(position));
            RadioButton cb = convertView.findViewById(R.id.chkMain);
            cb.setText(getItem(position).buttonTitle);
            if(getItem(position).buttonTitle.contains(specialSelectionTimeSelect)) {
                cb.setText("> 选择时间");
            }
            cb.setChecked(false);
            cb.setTextColor(getResources().getColor(R.color.chat_response_text));
            if(selectedSelection != null && selectedSelection.nextLeaf.equals(getItem(position).nextLeaf)){
                cb.setChecked(true);
                cb.setTextColor(getResources().getColor(R.color.chat_send_text));
            }
            cb.setTag(getItem(position));
            cb.setOnClickListener(MessageActivity.this::onSelectionClick);
            return convertView;
        }
    }

    public class CompanionCallAdapter extends ArrayAdapter<CompanionPhoneCall>{

        public CompanionCallAdapter(@NonNull @NotNull Context context) {
            super(context, R.layout.list_morning_call);
        }

        @NonNull
        @NotNull
        @Override
        public View getView(int position, @android.support.annotation.Nullable @Nullable View convertView, @NonNull @NotNull ViewGroup parent) {
            if(convertView == null){
                convertView = getLayoutInflater().inflate(R.layout.list_companion_call,null,false);
            }
            CompanionPhoneCall model = getItem(position);
            TextView titleView = convertView.findViewById(R.id.txtMorningCallTitle);
            TextView subtitleView = convertView.findViewById(R.id.txtMorningCallSubtitle);
            ImageButton btnPlay = convertView.findViewById(R.id.btnMorningCallListPlay);

            titleView.setText(model.title);
            subtitleView.setText(model.duration);

            btnPlay.setTag(model);
            btnPlay.setOnClickListener(MessageActivity.this::playOne);

            return convertView;
        }
    }

    void playOne(View v){
        CompanionPhoneCall call = (CompanionPhoneCall) v.getTag();
        ListPlayer.PlayEntry current = new ListPlayer.PlayEntry(call.path);
        List<ListPlayer.PlayEntry> playlist = new ArrayList<>();
        for (int i = 0;i<callAdapter.getCount();i++){
            CompanionPhoneCall holder= callAdapter.getItem(i);
            playlist.add(new ListPlayer.PlayEntry(holder.path));
        }
        PlayerActivity.StartPlayer(this,playlist,current);
    }

}
